import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Home from '@/views/homepage/home'
import Catagory from '@/views/homepage/catagory'
import Car from '@/views/homepage/car'
import User from '@/views/homepage/user'

const Login = () => import('@/views/login')
const Order = () => import('@/views/myorder')
const Detail = () => import('@/views/gooddetail')
const Homepage = () => import('@/views/homepage')
const Pay = () => import('@/views/pay')
const Search = () => import('@/views/search/index')
const List = () => import('@/views/search/list')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    // 动态路由传参，确认商品具体信息
    { path: '/detail/:id', component: Detail },
    {
      path: '/',
      component: Homepage,
      redirect: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/catagory', component: Catagory },
        { path: '/car', component: Car },
        { path: '/user', component: User }
      ]
    },
    { path: '/order', component: Order },
    { path: '/pay', component: Pay },
    { path: '/search', component: Search },
    { path: '/list', component: List }
  ]
})

// 全局前置导航-检查是否具有通行权限
// 权限页面
const userUrls = ['/pay', '/order']
router.beforeEach((to, from, next) => {
  if (!userUrls.includes(to.path)) {
    // 访问页面不属于权限页面：通行
    next()
    return
  }

  // 是权限页面，检查登录权证
  const token = store.state.user.userInfo.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
